import random
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from concurrent.futures import ThreadPoolExecutor


def click_login(driver, AC):
    # 点击登录按钮准备登录
    try:
        login_bt = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "id_l"))
        )
        time.sleep(6)
        AC.click(login_bt).perform()
        print("准备登录")
    except:
        click_login(driver, AC)


def put_in_account(driver, my_a):
    # 输入账户，并且回车
    try:
        account_input = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, '//*[@id="i0116"]'))
        )
        account_input.send_keys(my_a, Keys.ENTER)
        print("成功输入账户")
    except:
        put_in_account(driver, my_a)


def put_in_pass(driver, my_p):
    # 输入密码与回车
    try:
        pass_input = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, '//*[@id="i0118"]'))
        )
        pass_input.send_keys(my_p, Keys.ENTER)
        print("成功输入密码")
    except:
        put_in_pass(driver, my_p)


def click_certern(driver, AC):
    # 确认登录
    try:
        certain_bt = WebDriverWait(driver, 10, 1).until(
            EC.visibility_of_element_located(
                (By.XPATH,
                 '/html/body/div/form/div/div/div[2]/div[1]/div/div/div/div[2]/div/div[3]/div/div[2]/div/div[3]/div[2]/div/div/div[2]/input')
            ))
        AC.click(certain_bt).perform()
        # time.sleep(100)
    except:
        click_certern(driver, AC)


def search(driver):
    for i in range(35):  # 每次搜索获取3积分，根据个人等级调整循环次数
        random_number = str(random.randint(1, 50)) + str(i)
        query = WebDriverWait(driver, 10, 1).until(
            EC.visibility_of_element_located((By.XPATH, '//*[@id="sb_form_q"]'))
        )
        query.send_keys(random_number, Keys.ENTER)
        print('第', i + 1, '次完成')
        time.sleep(random.uniform(0.5, 1))


def get_point(url, my_a, my_p):
    driver = webdriver.Chrome()
    AC = ActionChains(driver)
    driver.get(url)

    click_login(driver, AC)

    put_in_account(driver, my_a)

    put_in_pass(driver, my_p)

    click_certern(driver, AC)

    search(driver)


if __name__ == "__main__":
    pool = ThreadPoolExecutor()

    pool.submit(get_point("https://www.bing.com/", "account", "password"))
